//
//  CommonlyDeviceSettingViewController.swift
//  ZhiTing
//
//  Created by macbook on 2022/4/2.
//

import UIKit
import CryptoSwift
import SwiftUI

class CommonlyDeviceSettingViewController: BaseViewController {
    private lazy var devices = [Device]()
    
    /// 常用设备的设备id数组
    private lazy var commonDeviceIds = [Int]()

    private var commons: [Device] {
        devices.filter { commonDeviceIds.contains($0.id) }
    }
    
    private var uncommons: [Device] {
        devices.filter { !commonDeviceIds.contains($0.id) }
    }


    private var commonlyTableIsFolded = false
    private var uncommonlyTableIsFolded = false

    //常用设备列表
    lazy var tableView = UITableView(frame: .zero, style: .plain).then {
        $0.delegate = self
        $0.dataSource = self
        $0.backgroundColor = .custom(.white_ffffff)
        $0.separatorStyle = .none
        if #available(iOS 15.0, *) {
            $0.sectionHeaderTopPadding = 0
        }
        //创建Cell
        $0.register(CommonlySettingCell.self, forCellReuseIdentifier: CommonlySettingCell.reusableIdentifier)
    }

    
    lazy var saveButton = CustomButton(buttonType:
                                                    .leftLoadingRightTitle(
                                                        normalModel:
                                                            .init(
                                                                title: "保存".localizedString,
                                                                titleColor: UIColor.custom(.white_ffffff).withAlphaComponent(1),
                                                                font: UIFont.font(size: ZTScaleValue(14), type: .bold),
                                                                backgroundColor: UIColor.custom(.blue_2da3f6).withAlphaComponent(1)
                                                            ),
                                                        lodingModel:
                                                            .init(
                                                                title: "保存中...".localizedString,
                                                                titleColor: UIColor.custom(.white_ffffff).withAlphaComponent(0.7),
                                                                font: UIFont.font(size: ZTScaleValue(14), type: .bold),
                                                                backgroundColor: UIColor.custom(.blue_2da3f6).withAlphaComponent(0.7)
                                                            )
                                                    )
    ).then {
        $0.layer.cornerRadius = 10
        $0.layer.masksToBounds = true
        $0.setTitleColor(.custom(.white_ffffff), for: .disabled)
        $0.addTarget(self, action: #selector(onClickDone), for: .touchUpInside)
    }

    
    // MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .custom(.gray_f6f8fd)
        // Do any additional setup after loading the view.
        Task {
            await getDeviceDatas()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.title = "常用设备设置".localizedString
        navigationController?.setNavigationBarHidden(false, animated: true)
        showLoadingView()
    }
    
    // MARK: - layout
    
    override func setupViews() {
        view.addSubview(tableView)
        view.addSubview(saveButton)
    }
    
    override func setupConstraints() {
        tableView.snp.makeConstraints {
            $0.top.equalTo(ZTScaleValue(10) + Screen.k_nav_height)
            $0.left.right.equalToSuperview()
            $0.bottom.equalTo(saveButton.snp.top).offset(-10)
        }
        
        
        saveButton.snp.makeConstraints {
            $0.bottom.equalToSuperview().offset(-Screen.bottomSafeAreaHeight - 10)
            $0.height.equalTo(50)
            $0.left.equalToSuperview().offset(15)
            $0.right.equalToSuperview().offset(-15)
        }

    }
    
    @objc private func onClickDone(){
        showLoadingView()
        ApiServiceManager.shared.updateUserCommonDeviceList(area: AuthManager.shared.currentArea, devices: commonDeviceIds) { [weak self] response in
            guard let self = self else { return }
            self.showToast(string: "保存成功".localizedString)
            self.navigationController?.popViewController(animated: true)
        } failureCallback: { [weak self] code, err in
            guard let self = self else { return }
            self.showToast(string: err)
            self.hideLoadingView()
        }

    }
    
    private func creatHeaderView(isCommonly: Bool) -> UIButton {
        
        let isFolded = isCommonly ? commonlyTableIsFolded : uncommonlyTableIsFolded
        
        let button = UIButton.init(type: .custom)
        button.backgroundColor = .custom(.white_ffffff)
        button.tag = isCommonly ? 0 : 1
        //标题
        let title = UILabel()
        title.font = .font(size: ZTScaleValue(16), type: .bold)
        title.textColor = .custom(.black_3f4663)
        title.text = isCommonly ? "常用的设备".localizedString : "非常用的设备".localizedString
        title.numberOfLines = 0
        button.addSubview(title)
        //添加约束

        //箭头
        let arrowIcon = UIImageView()
        if isFolded {//折叠
            arrowIcon.image = .assets(.arrow_down)
        }else{
            arrowIcon.image = .assets(.arrow_up)
        }
        button.addSubview(arrowIcon)
        
        
        title.snp.makeConstraints{
            $0.centerY.equalToSuperview()
            $0.left.equalTo(ZTScaleValue(14))
            $0.width.greaterThanOrEqualTo(ZTScaleValue(100))

        }
        arrowIcon.snp.makeConstraints{
            $0.centerY.equalToSuperview()
            $0.right.equalTo(-ZTScaleValue(15))
            $0.width.equalTo(ZTScaleValue(13.5))
            $0.height.equalTo(ZTScaleValue(8.0))
        }
                
        button.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside)
        return button
        
    }

    @objc private func buttonPress(sender: UIButton){
        switch sender.tag {
        case 0://常用
            commonlyTableIsFolded = !commonlyTableIsFolded
            tableView.reloadData()


        case 1://非常用
            uncommonlyTableIsFolded = !uncommonlyTableIsFolded
            tableView.reloadData()
            
        default:
            break
        }
    }
    
    @MainActor
    private func getDeviceDatas() async {
        do {
            showLoadingView()
            let currentArea = AuthManager.shared.currentArea
            let devices = try await AsyncApiService.deviceList(area: currentArea)
            let commonDevices = try await AsyncApiService.userCommonDeviceList(area: currentArea).map(\.id)
            self.devices = devices
            self.commonDeviceIds = commonDevices
            self.devices.forEach {
                if commonDeviceIds.contains($0.id) {
                    $0.is_common = true
                }
            }
            tableView.reloadData()
            hideLoadingView()

        } catch {
            hideLoadingView()
        }
    }
    
    override func navPop() {
        var ifAfterEdit = false
        let s1 = commonDeviceIds
            .sorted(by: <)
            .map{ String($0) }
            .joined()
        let s2 = devices
            .filter({ $0.is_common == true })
            .map(\.id)
            .sorted(by: <)
            .map{ String($0) }
            .joined()

        if s1 != s2 {
            ifAfterEdit = true
        }


        if ifAfterEdit {
            TipsAlertView.show(message: "退出后修改将丢失,是否退出?".localizedString) { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
    
    override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        var ifAfterEdit = false
        let s1 = commonDeviceIds
            .sorted(by: <)
            .map{ String($0) }
            .joined()
        let s2 = devices
            .filter({ $0.is_common == true })
            .map(\.id)
            .sorted(by: <)
            .map{ String($0) }
            .joined()

        if s1 != s2 {
            ifAfterEdit = true
        }

        if ifAfterEdit {
            TipsAlertView.show(message: "退出后修改将丢失,是否退出?".localizedString) { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }
            return false
        } else {
            return true
        }
    }
    

}


extension CommonlyDeviceSettingViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return ZTScaleValue(50)
    }

    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        //构建分区头
        if section == 0 { //非常用
            return creatHeaderView(isCommonly: false)
        }else{
            return creatHeaderView(isCommonly: true)
        }
    }

    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 { //非常用
            return uncommonlyTableIsFolded ? 0 : uncommons.count
            
        } else { //常用
            return commonlyTableIsFolded ? 0 : commons.count
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return ZTScaleValue(70)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CommonlySettingCell.reusableIdentifier, for: indexPath) as! CommonlySettingCell
        var model = Device()
        if indexPath.section == 0 {//非常用
            model = uncommons[indexPath.row]
            cell.executiveBtn.setImage(.assets(.commonly_Add), for: .normal)
            cell.executiveCallback = { [weak self] in
                guard let self = self else { return }
                self.commonDeviceIds.append(model.id)
                self.tableView.reloadData()
            }
            
        } else {
            model = commons[indexPath.row]
            cell.executiveBtn.setImage(.assets(.commonly_Delete), for: .normal)
            cell.executiveCallback = { [weak self] in
                guard let self = self else { return }
                self.commonDeviceIds.removeAll(where: { $0 == model.id })
                if let device = self.devices.first(where: { $0.id == model.id }) {
                    self.devices.removeAll(where: { $0.id == model.id })
                    self.devices.append(device)

                }
                
                self.tableView.reloadData()
            }
        }
        cell.selectionStyle = .none
        cell.title.text = model.name
        cell.iconImgView.setImage(urlString: model.logo_url, placeHolder: .assets(.default_device))
        return cell
    }
}
